package com.hmdp.service.impl;

import cn.hutool.core.bean.*;
import cn.hutool.core.util.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import com.hmdp.dto.*;
import com.hmdp.entity.*;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import com.sun.org.apache.xpath.internal.operations.*;
import jodd.util.*;
import org.apache.tomcat.util.buf.*;
import org.springframework.beans.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import javax.annotation.*;
import java.lang.String;
import java.util.*;
import java.util.stream.*;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IBlogService blogService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryBlogHot(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(record -> {
            blogSetUserInfo(record);
            isBlogLiked(record);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //查用户博客
        Blog blog = blogService.getById(id);
        if (blog == null) {
            return Result.fail("数据不存在");
        }
        blogSetUserInfo(blog);
        //查询用户是否已点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog){
        UserDTO user = UserHolder.getUser();
        if (user== null){
            return;
        }
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        blog.setIsLike(score !=null);

    }
    /**
     * 点赞单人 缓存
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //根据id 将 id和用户id放redis
        String key = BLOG_LIKED_KEY + id;
        String userId = UserHolder.getUser().getId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if(score == null){
            //3.如果未点赞，可以点赞
            //3.1 数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            //3.2 保存用户到Redis的set集合
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis()
                );
            }
            return Result.ok("点赞成功");
        }else{
            //4.如果已点赞，取消点赞
            //4.1 数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2 把用户从Redis的set集合移除
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key, userId);
                return Result.ok("取消点赞");
            }
        }
        return Result.fail("点赞失败");
    }
    //显示最新点赞的人Id
    @Override
    public Result queryBlogLikeUsers(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //最新点赞的5人
        Set<String> topFive = stringRedisTemplate.opsForZSet().reverseRange(key, 0, 4);
        if (topFive == null || topFive.isEmpty()){
            //0个人赞
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = topFive.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        //select * from user where id in (1,2,3,4,5) order by field(idsList)
        //查用户给DTO
        List<User> userList = userService.lambdaQuery()
                .in(User::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        List<UserDTO> userDTOList = userList.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSave = save(blog);
        if (!isSave){
            return Result.fail("发布失败");
        }
        // 3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).select("user_id").list();
        for (Follow follow : follows) {
            // 4.1.获取粉丝id
            Long userId = follow.getUserId();
            // 4.2.推送
            String key = FEED_KEY + userId;
            //key是粉丝的id value是博客id
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //分页查询关注的人的笔记
        Long userId = UserHolder.getUser().getId();//当前用户id
        //查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());//存放博客id
        long minTime = 0; //最新的博客时间
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(Objects.requireNonNull(typedTuple.getValue())));
            //获取时间戳 从最新到最后
            long Time = Objects.requireNonNull(typedTuple.getScore()).longValue();
            if (Time == minTime){
                os++;
            }else {
                minTime = Time;
                os=1;
            }

        }
        os = minTime == max ? os : os + offset;
        String idStr = StrUtil.join(",",ids);
        //根据id查询博客
        List<Blog> blogList = blogService.lambdaQuery()
                .in(Blog::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    private void blogSetUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
